#!/usr/bin/env python
# -*- coding: UTF-8-*-

from twisted.web import resource

class CorsResource(resource.Resource):
    """支持CORS的资源基类"""

    def render_OPTIONS(self, request):
        """处理CORS预检请求"""
        self._set_cors_headers(request)
        request.setResponseCode(200)
        return b''

    def _set_cors_headers(self, request):
        """设置CORS响应头"""
        # 只允许特定域名访问
        allowed_origins = [
            b'https://servicewechat.com',  # 微信小程序基础域名
            b'http://localhost:3000',  # 本地开发
            b'https://game.houdeyun.com'  # 你的网站域名
        ]
        origin = request.getHeader(b'Origin')

        if origin in allowed_origins:
            request.setHeader(b'Access-Control-Allow-Origin', origin)
        else:
            request.setHeader(b'Access-Control-Allow-Origin', b'')  # 不允许

        request.setHeader(b'Access-Control-Allow-Origin', b'*')
        request.setHeader(b'Access-Control-Allow-Methods', b'GET, POST, PUT, DELETE, OPTIONS')
        request.setHeader(b'Access-Control-Allow-Headers', b'Content-Type, Authorization')
        request.setHeader(b'Access-Control-Max-Age', b'86400')  # 24小时缓存
